package com.nc.mem.serial.graph.cust;

import java.nio.ByteBuffer;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.SortedMap;

import com.nc.mem.serial.graph.Representation;
import com.nc.mem.serial.graph.asm.GraphSerializerFactory;


public class MapHolder<K, V> implements Iterable<Map.Entry<K, V>> {

	final Map<K, V> src;

	byte flags;

	public MapHolder(final Map<K, V> map, final boolean keyOnlyPayload, final boolean valOnlyPayload) {
		this.src = map;

		flags = (byte) ((keyOnlyPayload ? 1 : 0) | (valOnlyPayload ? 1 << 1 : 0));
	}

	public Class<?> mapClass() {
		return src.getClass();
	}

	public boolean isKeyOnlyPayload() {
		return (flags & 1) != 0;
	}

	public boolean isValOnlyPayload() {
		return (flags & 1 << 1) != 0;
	}

	@Override
	public Iterator<Entry<K, V>> iterator() {

		return src.entrySet().iterator();
	}

	public int size() {
		return src.size();
	}

	public void writeKindAndSize(final ByteBuffer dest) {
		final Map<K, V> map = src;
		final Comparator<?> c = map instanceof SortedMap ? ((SortedMap<?, ?>) map).comparator() : null;
		final long s = map.size() << 1 | (c != null ? 1 : 0);

		Representation.writeLong(dest, s);

		if (c != null) {
			GraphSerializerFactory.serializer(c.getClass()).write(dest, c);
			Representation.writeLong(dest, s);
		}

	}

}
